package com.bluefox.hospital.service.impl;

import com.bluefox.common.web.exception.CustomRuntimeException;
import com.bluefox.hospital.model.RichText;
import com.bluefox.hospital.repository.RichTextRepository;
import com.bluefox.hospital.service.RichTextService;
import com.bluefox.uac.security.CustomAuthenticationToken;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;

/**
 * RichTextService 实现类
 *
 * @author Administrator
 */
@SuppressWarnings("all")
@Service
@Transactional
public class RichTextServiceImpl implements RichTextService {

    @Autowired
    private RichTextRepository richTextRepository;

    @Override
    @Transactional(readOnly = true)
    public RichText get(@NonNull Long id) {
        final RichText model = richTextRepository.findById(id).get();
        if (model == null) {
            throw new CustomRuntimeException("404", String.format("查找的资源[%s]不存在.", id));
        }
        return model;
    }

    @Override
    public RichText create(RichText model) {
        // TODO: 业务逻辑
        model.setOrderField(0);
        return richTextRepository.save(model);
    }

    @Override
    public RichText update(RichText model) {
        // TODO: 业务逻辑
        return richTextRepository.save(model);
    }

    @Override
    public void delete(@NonNull Long id) {
        // TODO: 业务逻辑
        richTextRepository.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<RichText> findAll(Pageable pageable) {
        // 从springSecurity中获取登录用户
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof CustomAuthenticationToken) {
            CustomAuthenticationToken token = (CustomAuthenticationToken) authentication;
            username = token.getDetails().getUsername();
        }
        Page<RichText> richTexts = null;
        if (StringUtils.isEmpty(username)) {
            throw new CustomRuntimeException("401", "用户未通过认证，请重新登录");
        } else if ("admin".equals(username) || "ADMIN".equals(username)) {
            // richTexts = richTextRepository.findAll(pageable);
            // 这是查询未审核的新闻
            richTexts = richTextRepository.findByStatus(0, pageable);
        } else {
            richTexts = richTextRepository.findByCreatedBy(username, pageable);
        }
        if (richTexts.getSize() <= 0) {
            return richTexts;
        } else {
            //去除大字段
            richTexts.getContent().forEach(richText -> {
                richText.setContent("");
            });
        }
        return richTexts;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<RichText> findAll(String type, Pageable pageable) {
        CustomAuthenticationToken token = (CustomAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String username = token.getDetails().getUsername();

        Page<RichText> richTexts = null;
        // 判断用户是否登录
        if (StringUtils.isEmpty(username)) {
            throw new CustomRuntimeException("401", "用户未通过认证，请重新登录");
            //判断登录的用户是否是admin
        } else if ("admin".equals(username) || "ADMIN".equals(username)) {
            // 类型不存在  这个在前面已经判断过了  一般不会发生
            if ("".equals(type) || null == type) {
                richTexts = richTextRepository.findAll(pageable);
                //类型存在 查询审核后的新闻
            } else {
                richTexts = richTextRepository.findByTypeAndStatus(type, 1, pageable);
            }
        } else {
            // 类型不存在  这个在前面已经判断过了  一般不会发生
            if ("".equals(type) || null == type) {
                richTexts = richTextRepository.findByCreatedBy(username, pageable);
                //类型存在 查询审核后的新闻
            } else {
                richTexts = richTextRepository.findByTypeAndCreatedByAndStatus(type, username, 1, pageable);
            }
        }
        if (null == richTexts && richTexts.getSize() <= 0) {
            return richTexts;
        } else {
            //去除大字段
            richTexts.getContent().forEach(richText -> {
                richText.setContent("");
            });
        }
        return richTexts;
    }

    @Override
    @Transactional(readOnly = true)
    public List<RichText> findTop6ByType(String type, Integer status) {
        List<RichText> richTexts = richTextRepository.findTop9ByTypeAndStatusOrderByOrderFieldDescCreatedDateDesc(type, status);
        richTexts.forEach(richText -> {
            /*List<String> imgs = getImg(richText.getContent());
            if (imgs.size() > 0) {
                richText.setContent(imgs.get(0));
            }*/
            richText.setContent("");
        });
        return richTexts;
    }

    public static List<String> getImg(String s) {
        String regex;
        List<String> list = new ArrayList<String>();
        regex = "src=\"(.*?)\"";
        Pattern pa = compile(regex, DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find()) {
            list.add(ma.group().substring(5, ma.group().length() - 1));
        }
        return list;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<RichText> findByTypeAndStatus(String type, Integer status, Pageable pageable) {
        Page<RichText> richTexts = richTextRepository.findByTypeAndStatus(type, status, pageable);
        richTexts.get().forEach(richText -> {
            richText.setContent("");
        });
        return richTexts;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<RichText> findAllWeb(Pageable pageable) {
        Page<RichText> richTexts = richTextRepository.findAll(pageable);

        return richTexts;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<RichText> findAllWeb(String type, Pageable pageable) {
        Page<RichText> richTexts = null;
        if ("".equals(type) || null == type) {
            richTexts = richTextRepository.findAll(pageable);
        } else {
            richTexts = richTextRepository.findByType(type, pageable);
        }
        //去除大字段
        richTexts.getContent().forEach(richText -> {
            richText.setContent("");
        });
        return richTexts;
    }

    /**
     *  获取数据库最大的排序值
     * @return
     */
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    private Integer queryMaxOrderField(String type) {
        return this.richTextRepository.queryMaxOrderField(type);
    }

    @Override
    public RichText roofPlacement(RichText model){
        model.setOrderField(queryMaxOrderField(model.getType())+1);
        return richTextRepository.save(model);
    }
}
